import React, { useState } from 'react'
import { Button, Form, Input, message, Modal } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { UpdateCollectionBody } from '../types/types.ts'
import { collectionService } from '@/domain/collection/service/collectionService.ts'

interface CreateCollectionModalProps {
  isModalOpen: boolean
  toggleIsModalOpen: () => void
  selectedCollectionId: number
}

const UpdateCollectionModal: React.FC<CreateCollectionModalProps> = ({
  isModalOpen,
  toggleIsModalOpen,
  selectedCollectionId,
}) => {
  const [form] = Form.useForm()

  const [loading, setLoading] = useState(false)
  async function UpdateCollection(
    collectionId: number,
    values: UpdateCollectionBody,
  ) {
    const resp = await collectionService.updateCollectionService(
      collectionId,
      values,
    )
    if (resp) {
      message.success('更新成功')
    } else {
      message.error('更新失败')
    }
  }
  const [collectionId] = useState(selectedCollectionId)
  const onFinishHandle = async (values: UpdateCollectionBody) => {
    setLoading(true)
    await UpdateCollection(collectionId, values)
    form.resetFields()
    toggleIsModalOpen()
  }

  return (
    <Modal open={isModalOpen} onCancel={toggleIsModalOpen} footer={null}>
      <div className="mb-4 text-center text-lg font-medium">编辑收藏夹</div>
      <Form form={form} autoComplete={'off'} onFinish={onFinishHandle}>
        <Form.Item
          name={'name'}
          rules={[
            { required: true, message: '请输入收藏夹名称' },
            { min: 2, message: '最少两个字符' },
            { max: 32, message: '最多 32 个字符' },
            {
              pattern: new RegExp('^[\\u4e00-\\u9fa5a-zA-Z0-9_+\\-]+$'),
              message: '只能包含中文、字母、数字、下划线、中划线',
            },
          ]}
        >
          <Input placeholder={'请输入收藏夹名称'} />
        </Form.Item>
        <Form.Item
          name={'description'}
          rules={[
            { max: 128, message: '最多 128 个字符' },
            {
              pattern: new RegExp('^[\\u4e00-\\u9fa5a-zA-Z0-9_+\\-]+$'),
              message: '只能包含中文、字母、数字、下划线、中划线',
            },
          ]}
        >
          <TextArea placeholder={'请输入收藏夹描述'} rows={4} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" block loading={loading}>
            更新
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default UpdateCollectionModal
